//
//  SafetyManageViewController.m
//  ZYZB
//
//  Created by ENERGY on 2018/7/11.
//  Copyright © 2018年 ENERGY. All rights reserved.
//

#import "SafetyManageViewController.h"
#import "SettingArrowTableViewCell.h"
#import "SettingSwitchTableViewCell.h"
#import "ChangePasswordViewController.h"
#import "ChangeGestureViewController.h"
#import "BankChangeCodeViewController.h"
#import "BankResetCodeViewController.h"
@interface SafetyManageViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong)UITableView * tableView;
@property (nonatomic, strong)NSMutableArray * arrowArr;
@property (nonatomic, strong)NSMutableArray * switchArr;
@property (nonatomic, strong)UIView * footerView;
@end
@implementation SafetyManageViewController(networking)
//修改支付密码
- (void)changePayCodeData{
    //    [self showprogressHUD];
    NSString * timeStr = [self currentTimeStr];
    //str
    NSDictionary * dic = @{
                           @"userName":[UserModel sharedInstanced].mobile,
                           @"t":timeStr
                           };
    //sign
    NSDictionary * signDic = @{
                               @"userName":[UserModel sharedInstanced].mobile,
                               @"t":timeStr,
                               @"merchantNo":@"80d709a97af1b8ab"
                               };
    SortMD5Code * md5Code = [[SortMD5Code alloc] init];
    NSString * jsonStr = [md5Code getJsonWithStrDic:dic withSignDic:signDic];
    NSData *postData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:@"http://120.78.157.132:82/index.php/passEdit/index"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //设置请求方式
    request.HTTPMethod = @"POST";
    //设置请求参数
    request.HTTPBody = postData;
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        [self hiddenProgressHUD];
        if (connectionError) {
            if (connectionError.code == -1001) {
                [self.view makeToast:@"请求网络超时，请稍后再试" duration:1 position:CSToastPositionCenter];
            }
        }else{
            NSDictionary *dictionary =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];//data解析为dictionary
            if (!dictionary) {
                NSLog(@"数据缺失");
                return;
            }
            NSDictionary * jsonData = [md5Code getNSDictionaryData:dictionary];//解析为字典数据
            if ([jsonData[@"code"] isEqualToString:@"000000"]) {
                BankChangeCodeViewController * vc = [[BankChangeCodeViewController alloc] init];
                vc.webURLStr = [jsonData[@"body"] objectForKey:@"shabaction"];
                vc.bankNeedInfoDic = @{
                                       @"merchantNo":[jsonData[@"body"] objectForKey:@"merchantNo"],
                                       @"keyEnc":[jsonData[@"body"] objectForKey:@"keyEnc"],
                                       @"merOrderNo":[jsonData[@"body"] objectForKey:@"merOrderNo"],
                                       @"jsonEnc":[jsonData[@"body"] objectForKey:@"jsonEnc"],
                                       @"sign":[jsonData[@"body"] objectForKey:@"sign"]};
                vc.sessionID = jsonData[@"session"];
                [self.navigationController pushViewController:vc animated:YES];
            }else{
                ShowMessage(jsonData[@"msg"]);
            }
        }
    }];
}
//重置支付密码
- (void)resetPayCodeData{
    //    [self showprogressHUD];
    NSString * timeStr = [self currentTimeStr];
    //str
    NSDictionary * dic = @{
                           @"userName":[UserModel sharedInstanced].mobile,
                           @"t":timeStr
                           };
    //sign
    NSDictionary * signDic = @{
                               @"userName":[UserModel sharedInstanced].mobile,
                               @"t":timeStr,
                               @"merchantNo":@"80d709a97af1b8ab"
                               };
    SortMD5Code * md5Code = [[SortMD5Code alloc] init];
    NSString * jsonStr = [md5Code getJsonWithStrDic:dic withSignDic:signDic];
    NSData *postData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:@"http://120.78.157.132:82/index.php/userCent/rePayPass"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //设置请求方式
    request.HTTPMethod = @"POST";
    //设置请求参数
    request.HTTPBody = postData;
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        [self hiddenProgressHUD];
        if (connectionError) {
            if (connectionError.code == -1001) {
                [self.view makeToast:@"请求网络超时，请稍后再试" duration:1 position:CSToastPositionCenter];
            }
        }else{
            NSDictionary *dictionary =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];//data解析为dictionary
            if (!dictionary) {
                NSLog(@"数据缺失");
                return;
            }
            NSDictionary * jsonData = [md5Code getNSDictionaryData:dictionary];//解析为字典数据
            if ([jsonData[@"code"] isEqualToString:@"000000"]) {
                BankResetCodeViewController * vc = [[BankResetCodeViewController alloc] init];
                vc.webURLStr = [jsonData[@"body"] objectForKey:@"shabaction"];
                vc.bankNeedInfoDic = @{
                                       @"merchantNo":[jsonData[@"body"] objectForKey:@"merchantNo"],
                                       @"keyEnc":[jsonData[@"body"] objectForKey:@"keyEnc"],
                                       @"merOrderNo":[jsonData[@"body"] objectForKey:@"merOrderNo"],
                                       @"jsonEnc":[jsonData[@"body"] objectForKey:@"jsonEnc"],
                                       @"sign":[jsonData[@"body"] objectForKey:@"sign"]};
                vc.sessionID = jsonData[@"session"];
                [self.navigationController pushViewController:vc animated:YES];
            }else{
                ShowMessage(jsonData[@"msg"]);
            }
        }
    }];
}
@end
@implementation SafetyManageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"安全管理";
    //返回按钮
    UIButton * backBtn = [[UIButton alloc] initWithFrame:CGRectMake(18/WIDTH_6_SCALE, 14/WIDTH_6_SCALE + 24 + 20, 24/WIDTH_6_SCALE, 30/WIDTH_6_SCALE)];
    [backBtn addTarget:self action:@selector(backBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [backBtn setImage:[UIImage imageNamed:@"out"] forState:UIControlStateNormal];
    UIBarButtonItem * leftItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    self.navigationItem.leftBarButtonItem = leftItem;
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    [self.view addSubview:self.tableView];
}
#pragma mark - init
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - NAVI_HEIGHT - BOTTOM_HEIGHT) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [_tableView registerClass:[SettingArrowTableViewCell class] forCellReuseIdentifier:NSStringFromClass([SettingArrowTableViewCell class])];
        [_tableView registerClass:[SettingSwitchTableViewCell class] forCellReuseIdentifier:NSStringFromClass([SettingSwitchTableViewCell class])];
        _tableView.tableFooterView = [UIView new];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = getColor(grayBGColor);
        _tableView.tableFooterView = self.footerView;
    }return _tableView;
}
- (UIView *)footerView{
    if (!_footerView) {
        _footerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 1/WIDTH_6_SCALE)];
        _footerView.backgroundColor = getColor(grayColor);
    }return _footerView;
}
- (NSMutableArray *)arrowArr{
    if (!_arrowArr) {
        _arrowArr = @[@{@"title":@"修改登录密码"},
                      @{@"title":@"修改支付密码"},
                      @{@"title":@"重置支付密码"},
                      @{@"title":@"修改手势密码"},
                      @{@"title":@"创建手势密码"}].mutableCopy;
    }return _arrowArr;
}
- (NSMutableArray *)switchArr{
    if (!_switchArr) {
        _switchArr = @[@{@"title":@"隐藏手势密码轨迹"}].mutableCopy;
    }return _switchArr;
}
#pragma mark - tableViewDelegate和tableViewDataSource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell * cell = nil;
    if (indexPath.row < self.arrowArr.count) {
        SettingArrowTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([SettingArrowTableViewCell class]) forIndexPath:indexPath];
        cell.model = self.arrowArr[indexPath.row];
        return cell;
    }else{
        SettingSwitchTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([SettingSwitchTableViewCell class]) forIndexPath:indexPath];
        cell.model = self.switchArr[indexPath.row - self.arrowArr.count];
        cell.lineView.hidden = YES;
        return cell;
    }
    return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.arrowArr.count + self.switchArr.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 56/WIDTH_6_SCALE;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0) {
        ChangePasswordViewController * changePasswordVC = [[ChangePasswordViewController alloc] init];
        [self.navigationController pushViewController:changePasswordVC animated:YES];
    }
    if (indexPath.row == 1) {//修改支付密码
        [self changePayCodeData];
    }
    if (indexPath.row == 2) {//重置支付密码
        [self resetPayCodeData];
    }
    if (indexPath.row == 3) {
//        ChangeGestureViewController * changeGestureVC = [[ChangeGestureViewController alloc] initWithUnlockType:ZLUnlockTypeValidatePsw];
//        [self presentViewController:changeGestureVC animated:YES completion:nil];
        ChangeGestureViewController * changeGestureVC = [[ChangeGestureViewController alloc] initWithUnlockType:ZLUnlockTypeValidatePsw];
        UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:changeGestureVC];
        [self.navigationController presentViewController:navi animated:YES completion:nil];
    }
    if (indexPath.row == 4) {
//        ChangeGestureViewController * changeGestureVC = [[ChangeGestureViewController alloc] initWithUnlockType:ZLUnlockTypeCreatePsw];
//        [self presentViewController:changeGestureVC animated:YES completion:nil];
        ChangeGestureViewController * changeGestureVC = [[ChangeGestureViewController alloc] initWithUnlockType:ZLUnlockTypeCreatePsw];
        UINavigationController* navi = [[UINavigationController alloc] initWithRootViewController:changeGestureVC];
        [self.navigationController presentViewController:navi animated:YES completion:nil];
    }
}
#pragma mark - action
- (void)backBtnClick:(UIButton *)sender{
    [self.navigationController popViewControllerAnimated:YES];
}
@end
